from peewee import *

db = MySQLDatabase('nemtocr', host='localhost', port=3800, user='root', password='!@mtg23YWZ^&')


class UniversityDocuments(Model):
    id = PrimaryKeyField()
    year = IntegerField()
    code = CharField(max_length=32)
    name = CharField(max_length=64)
    rules = TextField()
    is_deleted = IntegerField()

    class Meta:
        database = db  # This model uses the "spider" database.
        table_name = 'university_documents'  # 如果不指定，默认是person


    # 插入单条数据(返回新增id)
    def toInsert(self, row):
        try:
            return UniversityDocuments.insert(row).execute()
        except Exception as e:
            return ''

    # 批量插入数据
    def toInsertBatch(self, rows):
        with db.atomic():
            UniversityDocuments.insert_many(rows).execute()


    # 根据id，获取单条记录
    def getOne(self, id):
        try:
            return UniversityDocuments.select().where(UniversityDocuments.id == id).get()
        except Exception as e:
            return ''


    # 根据院校代码code，获取单条记录
    def getOneByCode(self, code):
        try:
            return UniversityDocuments.select().where(UniversityDocuments.code == code).order_by(UniversityDocuments.year.desc()).dicts().get()
        except Exception as e:
            return ''


    # 根据年份查询列表
    def getList(self, year):
        try:
            return UniversityDocuments.select().where(UniversityDocuments.year == year).dicts().execute()
        except Exception as e:
            print(e)
            return ''


    # 更新单条数据(返回影响记录数)
    def toUpdate(self, row):
        try:
            return UniversityDocuments.update(rules=row['rules']).where((UniversityDocuments.year == row['year']) & (UniversityDocuments.code == row['code'])).execute()
        except Exception as e:
            return ''


if __name__ == '__main__':
    unversity = UniversityDocuments()
    try:
        university_row = unversity.getOneByCode('10001')
        print(university_row)
    except Exception as e:
        print("except:", e)
